package fmtlog

import (
    "time"
    "os"
    "fmt"
    "bufio"
)

type fmtWriter struct {
	*bufio.Writer

	file   *os.File
	fname  string
	max    int64
	nbytes int64   // The number of bytes written to this file
	ctime  int      //YearDay
}

func NewFmtWriter(fname string, max int64) (wr *fmtWriter) {
	lname := logname(fname)
    f, e := os.OpenFile(lname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
    if e != nil {
    	panic(e)
    }

    st, e := os.Stat(lname)
    if e != nil {
    	panic(e)
    }

	wr = &fmtWriter{
			file  : f,
            fname : fname,
            max   : max,
            nbytes: st.Size(),
			ctime : time.Now().YearDay(),
		}

	wr.Writer = bufio.NewWriterSize(wr.file, SYNC_BUFFER_MAX)

	return
}

func (wr *fmtWriter) Sync() error {
	return wr.file.Sync()
}

func (wr *fmtWriter) Write(p []byte) (n int, e error) {
	n, e = wr.Writer.Write(p)
	wr.nbytes += int64(n)

	if e != nil {
		wr.Flush()
		wr.file.Close()
		return
	}

	//create log per day or log size > max size
	if wr.ctime != time.Now().YearDay() || wr.nbytes >= wr.max {
		wr.Flush()
		wr.file.Close()
		oname := logname(wr.fname)
		nname := lognowname(wr.fname)
		e = os.Rename(oname, nname)
		if e != nil {
			fmt.Printf("rename e = %v\n", e)
			return
		}

		e = fmt.Errorf("Rotate Log File")
	}

	return
}

func logname(fname string) string {
	return fname + ".log"
}

func lognowname(fname string) string {
    now := time.Now()
    return fmt.Sprintf("%s_%s-%d.log", fname, now.Format("2006-01-02"), now.Unix() % 86400)
}
